
from django.shortcuts import render,HttpResponse

from django.shortcuts import render, redirect

# Create your views here.
def search(request):
    return render(request, 'search.html')

def scenery(request):
    return render(request, 'scenery.html')

def base(request):
    return render(request, 'base.html')

def user_login(request):
    return render(request, "user_login.html")

def user_logout(request):
    return render(request,'user_logout.html')


def register(request):
    return render(request,'register.html')
def travel_group(request):
    return render(request,'travel_group.html')
def travel(request):
    return render(request,'travel.html')

def house(request):
    return render(request,'house.html')
def itinerary(request):
    return render(request,'itinerary.html')
def user_strategy(request):
    return render(request, "user_strategy.html")

def user_message_reminder(request):
    return render(request,"user_message_reminder.html")
def user_profile(request):
    return render(request,'user_profile.html')
def user_collections(request):
    return render(request,'user_collections.html')
def user_settings(request):
    return render(request,'user_settings.html')



from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.conf import settings
from .utils.baichuan_api import BaichuanAPI
import json

# 初始化百川API
baichuan_api = BaichuanAPI(settings.BAICHUAN_API_KEY)


@csrf_protect
def baichuan_search_api(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            query = data.get("query", "").strip()

            if not query:
                return JsonResponse({"success": False, "message": "搜索内容不能为空"})

            # 调用百川API搜索
            api_result = baichuan_api.search(query)
            return JsonResponse(api_result)

        except json.JSONDecodeError:
            return JsonResponse({
                "success": False,
                "message": "无效的请求格式"
            }, status=400)
        except Exception as e:
            return JsonResponse({
                "success": False,
                "message": f"服务器错误：{str(e)}"
            }, status=500)

    return JsonResponse({"success": False, "message": "仅支持POST请求"}, status=405)


def search_results(request):
    query = request.GET.get("query", "").strip()
    results = []

    if query:
        # 调用百川API获取结果
        api_result = baichuan_api.search(query)
        results = api_result.get("results", []) if api_result.get("success") else []

    return render(request, "results.html", {
        "query": query,
        "results": results,
        "count": len(results)
    })


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .utils.baichuan_api import BaichuanAPI  # 导入你的百川API类
from django.conf import settings
from .models import User
from django.views.decorators.csrf import csrf_exempt
import json


@csrf_exempt
def baichuan_search(request):
    if request.method == 'POST':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            query = data.get('query', '')

            if not query:
                return JsonResponse({
                    'success': False,
                    'message': '搜索内容不能为空'
                })

            # 初始化百川API客户端
            if not hasattr(settings, 'BAICHUAN_API_KEY') or not settings.BAICHUAN_API_KEY:
                return JsonResponse({
                    'success': False,
                    'message': '未配置百川API密钥'
                })

            baichuan = BaichuanAPI(settings.BAICHUAN_API_KEY)

            # 调用API
            result = baichuan.chat(query)

            return JsonResponse(result)

        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'message': '请求格式错误，应为JSON格式'
            })
        except Exception as e:
            # 输出详细错误信息到控制台
            import traceback
            print(f"搜索接口错误: {str(e)}")
            print(traceback.format_exc())  # 打印完整堆栈跟踪
            return JsonResponse({
                'success': False,
                'message': f'搜索过程中发生错误: {str(e)}'
            })
    else:
        return JsonResponse({
            'success': False,
            'message': '仅支持POST请求'
        })


from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login as auth_login
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json


# 显示登录页面
def login_page(request):
    # 如果用户已登录，直接重定向到首页
    if request.user.is_authenticated:
        return redirect('/search/')
    return render(request, 'login.html')


# 处理登录请求
@csrf_exempt
@require_http_methods(["POST"])  # 只允许POST请求
def login_view(request):
    try:
        # 解析请求数据
        data = json.loads(request.body)
        username = data.get('username', '').strip()
        password = data.get('password', '').strip()
        remember_me = data.get('remember_me', False)

        # 验证数据
        if not username or not password:
            return JsonResponse({
                'status': 'error',
                'message': '用户名和密码不能为空'
            }, status=400)

        # 使用Django内置认证系统验证用户
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # 登录用户
            auth_login(request, user)

            # 设置会话有效期：如果勾选"记住我"，则延长会话时间
            if not remember_me:
                request.session.set_expiry(0)  # 浏览器关闭时过期

            return JsonResponse({
                'status': 'success',
                'message': '登录成功',
                'redirect_url': '/search/'  # 登录后跳转的页面
            })
        else:
            return JsonResponse({
                'status': 'error',
                'message': '用户名或密码不正确'
            }, status=401)

    except json.JSONDecodeError:
        return JsonResponse({
            'status': 'error',
            'message': '无效的请求数据格式'
        }, status=400)
    except Exception as e:
        # 实际生产环境中应记录错误日志
        return JsonResponse({
            'status': 'error',
            'message': '服务器内部错误'
        }, status=500)



from django.contrib.auth import authenticate

# views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import RegisterForm


def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '注册成功！请登录。')
            return redirect('user_login')  # 替换为您的登录URL名称
        else:
            # 将表单错误转换为消息
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{error}")
    else:
        form = RegisterForm()

    return render(request, 'register.html', {'form': form})







from django.http import JsonResponse
from django.views.decorators.http import require_POST, require_GET
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from .models import Strategy, Favorite
from django.conf import settings
from django.contrib.auth import get_user_model

@require_GET
def check_all_favorites(request):
    """检查当前用户所有已收藏的攻略"""
    if not request.user.is_authenticated:
        return JsonResponse({'favorites': []})

    # 获取当前用户收藏的所有攻略ID
    favorite_strategies = Favorite.objects.filter(
        user=request.user
    ).values_list('strategy_id', flat=True)

    return JsonResponse({
        'favorites': list(favorite_strategies)
    })


@require_POST
@login_required
def add_favorite(request, strategy_id):
    """添加收藏"""
    User = get_user_model()
    strategy = get_object_or_404(Strategy, id=strategy_id)

    # 调试信息
    print(f"用户 {request.user.id} 尝试收藏攻略 {strategy_id}")

    # 检查是否已收藏
    if Favorite.objects.filter(user=request.user, strategy=strategy).exists():
        print(f"用户 {request.user.id} 已经收藏过攻略 {strategy_id}")
        return JsonResponse({
            'success': False,
            'message': '已经收藏过了'
        }, status=400)

    try:
        Favorite.objects.create(
            user=request.user,
            strategy=strategy
        )
        print(f"用户 {request.user.id} 成功收藏攻略 {strategy_id}")
        return JsonResponse({'success': True, 'message': '收藏成功'})
    except Exception as e:
        print(f"用户 {request.user.id} 收藏攻略 {strategy_id} 失败: {str(e)}")
        return JsonResponse({
            'success': False,
            'message': f'收藏失败: {str(e)}'
        }, status=500)


@require_POST
@login_required
def remove_favorite(request, strategy_id):
    """取消收藏"""
    User = get_user_model()  # 获取正确的用户模型
    strategy = get_object_or_404(Strategy, id=strategy_id)

    # 删除收藏
    deleted_count, _ = Favorite.objects.filter(
        user=request.user,
        strategy=strategy
    ).delete()

    if deleted_count > 0:
        return JsonResponse({'success': True, 'message': '取消收藏成功'})
    else:
        return JsonResponse({
            'success': False,
            'message': '未找到收藏记录'
        }, status=404)

@login_required
def favorite_list(request):
    """用户收藏列表页面"""
    favorites = Favorite.objects.filter(user=request.user).select_related('strategy')
    return render(request, 'favorite_list.html', {
        'favorites': favorites
    })

from django.contrib.auth import logout
from django.http import JsonResponse

def user_logout_view(request):
    if request.method == 'POST':
        # 关键：销毁Django后端会话
        logout(request)
        return JsonResponse({'status': 'success', 'message': '退出成功'})
    return JsonResponse({'status': 'error', 'message': '无效请求'}, status=400)


# 在文件顶部添加导入
from django.contrib.auth.decorators import login_required

# 修改 itinerary 函数，添加登录要求
@login_required(login_url='user_login')  # 指定登录页面URL
def itinerary(request):
    return render(request, 'itinerary.html')


@require_GET
def check_all_favorites(request):
    """检查当前用户所有已收藏的攻略"""
    User = get_user_model()  # 获取正确的用户模型

    if not request.user.is_authenticated:
        return JsonResponse({'success': True, 'favorites': []})

    # 获取当前用户收藏的所有攻略ID
    favorite_strategies = Favorite.objects.filter(
        user=request.user
    ).values_list('strategy_id', flat=True)

    return JsonResponse({
        'success': True,
        'favorites': list(favorite_strategies)
    })
